<script setup lang="ts">
import { useMobileCode } from '@/composables';
import { bindMobile, loginByQQ } from '@/services/user';
import { useUserStore } from '@/stores';
import { User } from '@/types/user';
import { codeRules, mobileRules } from '@/utils/rules';
import { showSuccessToast } from 'vant';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
/*global QC */
//获取openid
const mobile=ref()
const code=ref()
const openId=ref<string>('')
const isNeedBin=ref(false)
const route=useRoute()
onMounted(()=>{
 
  if(QC.Login.check()){
    QC.Login.getMe((id:string)=>{
    openId.value=id
    loginByQQ(openId.value).then((res)=>{
     //登录成功

     successLoagin(res.data)
    }).catch(()=>{
     //登陆失败
     isNeedBin.value=true
    })
    })
  }
})
//绑定手机号
const bind=async()=>{
   const res=await bindMobile({
    mobile:mobile.value,
    code:code.value,
    openId:openId.value
   })
   successLoagin(res.data)
}
const store=useUserStore()
const router=useRouter()
const successLoagin=(res:User)=>{
   //存储信息
   store.setUser(res)
   //跳转页面
   router.replace(store.returnUrl || '/user')
   showSuccessToast('登陆成功')
   store.setReturnUrl('')
}
const {time,form,sendCode}=useMobileCode(mobile,'bindMobile')
</script>
<template>
  <div class="login-page" v-if="isNeedBin">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" ref="form">
      <van-field :rules="mobileRules" v-model="mobile" name="mobile" placeholder="请输入手机号"></van-field>
      <van-field :rules="codeRules" v-model="code" name="code" placeholder="请输入验证码">
        <template #button>
          <span class="btn-send"
          :class="{active:time>0}" @click="sendCode">{{time>0? `${time}s后重新发送`:"发送验证码"}}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button
          style="margin-top: 50px"
          block
          round
          type="primary"
          native-type="submit"
          @click="bind"
        >
          立即绑定
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
